package com.lancoo.answer.view.fragment.option

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.fragment.app.Fragment
import com.lancoo.answer.R
import com.lancoo.answer.component.InteractWebView
import com.lancoo.answer.databinding.EvFragmentOptionBinding
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.ConstantBean.Companion.taskState
import com.lancoo.answer.model.TaskState
import com.lancoo.answer.model.bean.EvOptionBean
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.view.base.BaseVMFragment
import com.lancoo.answer.widget.SplitView
import com.rxjava.rxlife.ObservableLife
import com.rxjava.rxlife.RxLife
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit

/**
 * Created by Dadong on 2021/12/2
 * Describe: 词汇匹配，短文匹配
 *
 */
class OptionFragment : BaseVMFragment<EvFragmentOptionBinding>() {
    private val TAG = "OptionFragment"

    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var childIndex = 0
    private var defaultLoadIndex = 0
    private var itemIndex = -1
    private var mItemIndex = 0
    private var itemSortIndex: String = "" //当前选择的序号
    private var isFinish = false
    private lateinit var multiChildFragment: MultiChildFragment
    private var menuVisible = false
    private var convertView: View? = null


    companion object {
        fun loadFragment(
            typeIndex: Int,
            quesIndex: Int,
            defaultLoadChildIndex: Int,
            defaultLoadItemIndex: Int
        ): Fragment {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultLoadChildIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADITEMINDEX, defaultLoadItemIndex)
            val optionFragment = OptionFragment()
            optionFragment.arguments = mBundle
            return optionFragment
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.ev_fragment_option
    }

    override fun initView(view: View) {
        convertView = view
        EventBus.getDefault().register(this);
    }

    override fun initData() {
        if (ConstantBean.constantExamBean == null) {
            return
        }
        val kindBeanList = ConstantBean.constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        childIndex = requireArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX)
        defaultLoadIndex = requireArguments().getInt(AnswerConstant.KEY_LOADITEMINDEX)
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
        childIndex = ques.currentLoadChildIndex
        defaultLoadIndex = ques.ChildList!![childIndex].currentLoadItemIndex
        if (childIndex == -1) {
            childIndex = 0
        }
        var size = ques.ChildList!!.size
        if (defaultLoadIndex >= 0 && defaultLoadIndex < ques.ChildList!![childIndex].ItemList!!.size) {
            itemSortIndex =
                ques.ChildList!![childIndex].ItemList!![defaultLoadIndex].ItemSortIndex!!
        } else {
            itemSortIndex = ques.ChildList!![0].ItemList!![0].ItemSortIndex!!
        }
        mBinding.childStatisticsView.setQues(ques)
        if (childIndex == -1) {
            childIndex = 0
        }
        setInteractWebView()
        initAnswer()
    }

    //加载题干
    private fun setInteractWebView() {
        mBinding.interactWv.setIsIndentation(ques.ChildList!![childIndex].IsIndentChildAsk)
        mBinding.interactWv.setQues(ques)
        var childAsk = ""
        var dealAsk = ""
        ques.ChildList!!.forEach {
            dealAsk = it.ChildAsk!!
            if (ques.SpecialFeatureCodes == "47|101") {
                dealAsk =
                    it.ChildAsk?.replaceFirst(">", ">${it.ItemList!![0].SortIndex}. ")!!
            }
            childAsk += dealAsk
        }
        mBinding.interactWv.initWebView(
            requireActivity(),
            childAsk,
            object : InteractWebView.Callback {
                override fun finishCallback() {

                    if (taskState == TaskState.TRAINING) {
                        Observable.timer(200, TimeUnit.MILLISECONDS) //必须加延时才能算准高度
                            .observeOn(AndroidSchedulers.mainThread())
                            .`as`<ObservableLife<Long>>(RxLife.`as`<Long>(this@OptionFragment))
                            .subscribe { aLong: Long? ->
                                if (arguments == null) {
                                    return@subscribe
                                }
                                openPalette()
                            }
                    }
                    initLayout()
                    wvLoadUrl(itemSortIndex)
                    mBinding.interactWv.showOrHideAnalysisButton(0)
                    adjustFontSize()
                }

                override fun clickCallback(position: String) {
                    itemSortIndex = position
                    wvLoadUrl(position)

                }
            }
        )
    }

    private fun openPalette() {
        val sharedPreferences =
            requireContext().getSharedPreferences(AnswerConstant.SP_ANSWER_NAME, Context.MODE_PRIVATE)
        val openDash = sharedPreferences.getBoolean(AnswerConstant.SP_OPEN_DASH, false)
        if (openDash) {
            mBinding.interactWv.openPalette()
        } else {
            mBinding.interactWv.closePalette()
        }
    }

    //答题点下划线，高亮等等绘制
    private fun wvLoadUrl(position: String = "-1") {
        mBinding.interactWv.scrollPosition(position)
        ques.ChildList!!.forEach {
            it.ItemList!!.forEachIndexed { index, item ->
                mBinding.interactWv.loadUrl(
                    item,
                    position == item.ItemSortIndex.toString()
                )
            }
        }
    }

    //作答
    private fun initAnswer() {
        multiChildFragment =
            MultiChildFragment.loadFragment(
                typeIndex,
                quesIndex,
                childIndex
            ) as MultiChildFragment
        multiChildFragment.setChooseCallback(object : SingleOptionFragment.ChooseCallback {
            override fun clickCallback(item: EvOptionBean) {
                val position = getRealIndex()
                ques.ChildList!![childIndex].ItemList!![position].StuAnswer = item.OptionIndex
                if (ques.SpecialFeatureCodes == "47|101") { //适配高职
                    mItemIndex = getItemIndex()
                    mItemIndex += 1
                    dealItemIndexOverSize()
                    itemSortIndex = getItemSortIndex()
                } else {
                    itemSortIndex = (itemSortIndex.toInt() + 1).toString()
                    dealOverSize()
                }
                wvLoadUrl(itemSortIndex)
                if (isFinish) {
                    multiChildFragment.nextChildAsk()
                }
            }
        })

        multiChildFragment.setPageChangeCallback(object : MultiChildFragment.PageChangeCallback {
            override fun callback(position: Int) {
                if (itemIndex == -1) {
                    itemIndex = 0
                }
                childIndex = position
                itemSortIndex = ques.ChildList!![childIndex].ItemList!![itemIndex].ItemSortIndex!!
                wvLoadUrl(itemSortIndex)
                itemIndex = -1
            }
        })
        childFragmentManager
            .beginTransaction()
            .replace(mBinding.flAnswer.id, multiChildFragment!!, TAG)
            .commit()
    }

    //处理itemSortIndex超过范围的情况
    fun dealOverSize() {
        val size = ques.ChildList!![childIndex].ItemList!!.size
        val maxIndex = ques.ChildList!![childIndex].ItemList!![size - 1].ItemSortIndex!!
        if (itemSortIndex.toInt() > maxIndex.toInt()) {
            itemSortIndex = maxIndex
            isFinish = true
        } else {
            isFinish = false
        }
    }

    fun dealItemIndexOverSize() {
        val size = ques.ChildList!![childIndex].ItemList!!.size
        val childSize = ques.ChildList!!.size
        val maxIndex = ques.ChildList!![childSize - 1].ItemList!![size - 1].itemIndex
        if (mItemIndex > maxIndex.toInt()) {
            mItemIndex = maxIndex
            isFinish = true
        } else {
            isFinish = false
        }
    }

    //获取序号在ItemList 中的位置
    fun getRealIndex(): Int {
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { itemIndex, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    childIndex = index
                    return itemIndex
                }
            }
        }
        return 0
    }

    fun getChildIndex(): Int {
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { itemIndex, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    childIndex = index
                    return childIndex
                }
            }
        }
        return 0
    }

    fun getItemIndex(): Int {
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { itemIndex, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    childIndex = index
                    return item.itemIndex
                }
            }
        }
        return 0
    }

    fun getItemSortIndex(): String {
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { _, item ->
                if (item.itemIndex == mItemIndex) {
                    childIndex = index
                    return item.ItemSortIndex ?: "0"
                }
            }
        }
        return "0"
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetPosition(position: Int?) {
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    /**
     * 跳转到指定小题
     * @param itemIndex 答题点下标
     */
    fun jumpToAimChildFragment(childIndex: Int, itemIndex: Int) {
        if (mBinding != null) {
            Handler().postDelayed({
                itemSortIndex = ques.ChildList!![childIndex].ItemList!![itemIndex].ItemSortIndex!!
                this.childIndex = childIndex
                this.itemIndex = itemIndex
                wvLoadUrl(itemSortIndex)
                multiChildFragment.setCurrentItem(childIndex)
            }, 200)
        }
    }

    fun adjustFontSize() {
        mBinding.interactWv.setFontSize()
        multiChildFragment.adjustFontSize()
    }

    fun initLayout() {
        if (convertView == null) {
            return
        }
        val splitView: SplitView = convertView!!.findViewById<SplitView>(R.id.split_view)
        Single.timer(250, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .`as`(RxLife.`as`(this))
            .subscribe({ splitView.initLayout(0.5f) }) { throwable: Throwable? -> }
    }

    fun markQuestion() {
        var isShow = 0
        ques.ChildList!!.forEachIndexed { index, child ->
            child.ItemList!!.forEachIndexed { itemIndex, item ->
                if (item.ItemSortIndex == itemSortIndex) {
                    isShow = if (item.itemMark) { //
                        0
                    } else {
                        1
                    }
                    item.itemMark = !item.itemMark
                }
            }
        }
        val flagIndex = "znbkflag${itemSortIndex}"
        mBinding.interactWv.showFlag(flagIndex, isShow)
    }
}